﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data.Sql;
using System.Data;


namespace Task5
{
   

    class DBHelper
    {

        //数据库连接字符串
        public static string connStr = "server=.;database=Uses;Integrated Security=true";
        //数据库连接对象
        public static SqlConnection conn = null;
        //初始化数据库连接
        private static void InitConnectiont()
        {
            if (conn==null)
            {
                conn = new SqlConnection(connStr);
            }
            if (conn.State==ConnectionState.Closed)
            {
                conn.Open();
            }
            if (conn.State==ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }
        //执行查询操作，获取DataReader
        public static SqlDataReader GetDataReader(string sqlStr)
        {
            InitConnectiont();
            SqlCommand cmd = new SqlCommand(sqlStr,conn);
          
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        
        
        //执行增，删，改操作
        public static bool ExecuteNonQuery(string sqlStr)
        {
            InitConnectiont();
            SqlCommand cmd = new SqlCommand(sqlStr,conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result > 0;
        }
        //执行集合函数操作
        public static object ExecuteScalar(string sqlStr)
        {
            InitConnectiont();
            SqlCommand cmd = new SqlCommand(sqlStr,conn);
            object result = cmd.ExecuteScalar();
            conn.Close();
            return result;
        }
    }
}
